package com.example.blueconn.activity;

import android.Manifest;
import android.content.Intent;
import android.widget.Toast;

import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.Observer;

import com.clj.fastble.BleManager;
import com.example.blueconn.Constant;
import com.example.blueconn.R;
import com.example.blueconn.databinding.ActivityMainBinding;
import com.example.blueconn.fragment.HomeFragment;
import com.example.blueconn.fragment.ReportFragment;
import com.example.blueconn.fragment.ShowDetailFragment;
import com.example.blueconn.fragment.listener.CallListener;
import com.example.blueconn.manager.DataMgr;
import com.example.blueconn.manager.FastBleManager;
import com.example.blueconn.manager.PreferenceManager;
import com.example.blueconn.utils.DataUtils;
import com.example.blueconn.utils.StringUtils;
import com.google.android.material.tabs.TabLayout;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;
import com.tbruyelle.rxpermissions3.RxPermissions;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseActivity implements CallListener {
    private static final String TAG = "MainActivity";

    private ActivityMainBinding mainBinding;
    private List<Fragment> fragmentList = new ArrayList<>();


    @Override
    protected void initView() {
        super.initView();
        mainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        requestPermission();
//        配置menu
        initTopMenu();

        fragmentList = DataGenerator.getFragments(this);
        //配置tab
        TabLayout.Tab reportTab = mainBinding.tabLayout.newTab()
                .setCustomView(DataGenerator.getTabView(this, 0));
        TabLayout.Tab chartTab = mainBinding.tabLayout.newTab()
                .setCustomView(DataGenerator.getTabView(this, 1));
        TabLayout.Tab homeTab = mainBinding.tabLayout.newTab()
                .setCustomView(DataGenerator.getTabView(this, 2));
        mainBinding.tabLayout.addTab(reportTab);
        mainBinding.tabLayout.addTab(chartTab);
        mainBinding.tabLayout.addTab(homeTab);
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.add(R.id.container, fragmentList.get(0), ReportFragment.TAG);
        fragmentTransaction.commitAllowingStateLoss();
        mainBinding.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                onTabItemSelected(tab.getPosition());

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    @Override
    protected void initListener() {
        mainBinding.sbCheck.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                DataMgr.LTSwitch.postValue(2);
            } else {
                DataMgr.LTSwitch.postValue(1);
            }
        });
    }

    private void requestPermission() {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions
                .requestEach(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)
                .subscribe(permission -> {

                });
    }

    private void initTopMenu() {
        mainBinding.moreBtn.setOnClickListener(v -> showBottomSheetList());
        initBlTopBar();
        FastBleManager.recon.observe(this, aBoolean -> initBlTopBar());
        FastBleManager.connTipMsg.observe(this, integer -> {
            if (integer == 2) {
                Toast.makeText(this, "设备连接失败", Toast.LENGTH_SHORT).show();
            } else if (integer == 3) {
                initBlTopBar();
                mainBinding.deviceState.setImageResource(R.drawable.ic_device_connted);
            } else if (integer == 4) {
                mainBinding.deviceState.setImageResource(R.drawable.ic_device_disconnected);
                Toast.makeText(this, "设备断开连接", Toast.LENGTH_SHORT).show();
            }
        });
        mainBinding.deviceState.setOnClickListener(v -> {
            String macAddress = PreferenceManager.getInstance().getString(Constant.BL_MAC_ADDRESS);
            boolean isConn = BleManager.getInstance().isConnected(macAddress);
            if (isConn) {
                Toast.makeText(this, "设备已经连接！", Toast.LENGTH_SHORT).show();
                return;
            }
            Toast.makeText(this, "开始连接设备！", Toast.LENGTH_SHORT).show();
            initBlTopBar();
        });
        mainBinding.blArea.setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, CommonActivity.class);
            intent.putExtra(Constant.APP_BAR_TITLE, getString(R.string.bl_select_str));
            intent.putExtra(Constant.FRAGMENT_TAG, Constant.BL_SELECT_PAGER);
            startActivity(intent);
        });
        mainBinding.connMsg.setOnClickListener(v -> {
            FastBleManager.getInstance().writeData(DataUtils.openDetectMode());
        });
        DataMgr.XSOk.observe(this, aBoolean -> {
            if (aBoolean != null && aBoolean) {
                mainBinding.connMsg.setTextColor(ContextCompat.getColor(this, R.color.green));
            }
        });
    }

    private void initBlTopBar() {
        if (!BleManager.getInstance().isBlueEnable()) {
            BleManager.getInstance().enableBluetooth();
        }
        String macAddress = PreferenceManager.getInstance().getString(Constant.BL_MAC_ADDRESS);
        if (StringUtils.isEmpty(macAddress)) {
            mainBinding.blName.setText("请先连接蓝牙");
        } else {
            FastBleManager.getInstance().connect(macAddress);
            String name = PreferenceManager.getInstance().getString(Constant.BL_MAC_NAME);
            if (StringUtils.isEmpty(name)) {
                mainBinding.blName.setText("未知设备");
            } else {
                mainBinding.blName.setText(name);
            }
            mainBinding.macAddress.setText(macAddress);
        }
    }

    private void showBottomSheetList() {
        new QMUIBottomSheet.BottomListSheetBuilder(this)
                .addItem(getString(R.string.view_params))
                .addItem(getString(R.string.send_params))
                .addItem(getString(R.string.reboot_device))
                .addItem(getString(R.string.save_to_doc))
                .setOnSheetItemClickListener((dialog, itemView, position, tag) -> {
                    dialog.dismiss();
                    switch (position) {
                        case 0:
//                            Intent viewParamIntent = new Intent(MainActivity.this, CommonActivity.class);
//                            viewParamIntent.putExtra(Constant.APP_BAR_TITLE, getString(R.string.bl_view_params));
//                            viewParamIntent.putExtra(Constant.FRAGMENT_TAG, Constant.BL_VIEW_PARAM);
//                            startActivity(viewParamIntent);
                            Toast.makeText(this, "该功能暂未开放", Toast.LENGTH_SHORT).show();
                            break;
                        case 1:
                            Intent intent = new Intent(MainActivity.this, CommonActivity.class);
                            intent.putExtra(Constant.APP_BAR_TITLE, getString(R.string.bl_send_params));
                            intent.putExtra(Constant.FRAGMENT_TAG, Constant.BL_SEND_PARAM);
                            startActivity(intent);
                            break;
                        case 2:
//                                startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS));
//                            DialogUtils.confirmDialog(MainActivity.this, "提示", "确定要清除所有数据吗？",
//                                    (dialog12, index) -> dialog12.dismiss(), (dialog1, index) -> {
//                                        DataMgr.clearDealData();
//                                        ChartMgr.clearChartData();
//                                        dialog1.dismiss();
//                                    });
                            FastBleManager.getInstance().writeData(DataUtils.rebootDevice());
                            break;
                        case 3:
                            startActivity(new Intent(MainActivity.this, SaveDocActivity.class));
                            break;
                        default:
                            break;
                    }
                })
                .build()
                .show();
    }

    private void onTabItemSelected(int position) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        Fragment reportFragment = getSupportFragmentManager().findFragmentByTag(ReportFragment.TAG);
        Fragment homeFragment = getSupportFragmentManager().findFragmentByTag(HomeFragment.TAG);
        Fragment showDetailFragment = getSupportFragmentManager().findFragmentByTag(ShowDetailFragment.TAG);
        switch (position) {
            case 1:
                if (showDetailFragment != null) {
                    fragmentTransaction.show(showDetailFragment);
                } else {
                    fragmentTransaction.add(R.id.container, fragmentList.get(1), ShowDetailFragment.TAG);
                }
                if (reportFragment != null) {
                    fragmentTransaction.hide(reportFragment);
                }
                if (homeFragment != null) {
                    fragmentTransaction.hide(homeFragment);
                }
                break;
            case 2:
                if (homeFragment != null) {
                    fragmentTransaction.show(homeFragment);
                } else {
                    fragmentTransaction.add(R.id.container, fragmentList.get(2), HomeFragment.TAG);
                }
                if (reportFragment != null) {
                    fragmentTransaction.hide(reportFragment);
                }
                if (showDetailFragment != null) {
                    fragmentTransaction.hide(showDetailFragment);
                }
                break;
            case 0:
            default:
                if (reportFragment != null) {
                    fragmentTransaction.show(reportFragment);
                } else {
                    fragmentTransaction.add(R.id.container, fragmentList.get(0), ReportFragment.TAG);
                }
                if (showDetailFragment != null) {
                    fragmentTransaction.hide(showDetailFragment);
                }
                if (homeFragment != null) {
                    fragmentTransaction.hide(homeFragment);
                }
                break;
        }
        fragmentTransaction.commitAllowingStateLoss();
    }

    @Override
    public void callMethod(int position, int num, boolean isLight) {
        TabLayout.Tab tabAt = mainBinding.tabLayout.getTabAt(position);
        ShowDetailFragment fragment = (ShowDetailFragment) fragmentList.get(1);
        fragment.setDeviceNum(num, isLight);
        mainBinding.tabLayout.selectTab(tabAt);
    }
}